package org.wmq.positiontoshop.controller;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.wmq.positiontoshop.common.Result;
import org.wmq.positiontoshop.model.DO.User;
import org.wmq.positiontoshop.model.DTO.LoginDTO;
import org.wmq.positiontoshop.model.DTO.RegisterDTO;
import org.wmq.positiontoshop.service.UserService;

import java.util.UUID;

@RestController
@RequestMapping("/auth")
@Slf4j
public class LoginController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginDTO loginDTO){
        User user = this.userService.getByNameAndPassword(loginDTO.getUsername(), loginDTO.getPassword());
        if (user == null){
            log.error("user login failed, loginDTO={}",loginDTO);
            return Result.error("用户名或密码错误");
        }
        String token = UUID.randomUUID().toString();
        this.redisTemplate.opsForValue().set("token:" + token, JSON.toJSONString(user));
        return Result.success(token);
    }

    @PostMapping("/register")
    public Result<Void> register(@RequestBody RegisterDTO registerDTO){
        long count = this.userService.countByName(registerDTO.getUsername());
        if (count > 0){
            log.error("user register failed, registerDTO={},because name is exists",registerDTO);
            return Result.error("用户名已存在");
        }
        User user = new User();
        user.setName(registerDTO.getUsername());
        user.setPassword(registerDTO.getPassword());
        boolean save = this.userService.save(user);
        if (save){
            log.info("user register success, registerDTO={}",registerDTO);
            return Result.success();
        }else{
            log.error("user register failed, registerDTO={},because save user failed",registerDTO);
            return Result.error("REGISTER_FAILED");
        }
    }

}